/**
 * 卡片标签页
 */

import React, { Component } from 'react';
import { Card } from 'antd';
import { isEmpty } from '../common';

import { getUITabs } from '../uiConfig';

import UITabPanel from './UITabPanel';
import UIIcon from './UIIcon';
import update from 'immutability-helper'


export default class UICardTabs extends Component {

    constructor(props) {

        super(props);

        let tabConfig = getUITabs(props.tabConfigId);

        this.state = {
            loading: false,
            data: null,
            tabConfig: tabConfig,
            tabKey: isEmpty(props.activeTabKey) !== true ? props.activeTabKey : tabConfig.tabPageList[0].name,
        };

    }

    //try to remove tab
    removeTab(tabIndex) {
        this.setState(
            update(this.state,{
                tabConfig:{tabPageList:{$splice:[[tabIndex,1]]}}
            })
        )
    }

    getParent = () => {
        return this.props.parent;
    }

    componentDidMount() {

        setTimeout(() => {
            this.state.tabConfig.tabPageList.forEach(tab => {
                if (tab.name === this.state.tabKey && this.tabPanelRouter !== null) {
                    this.tabPanelRouter.goto(tab.compentclass);
                }
            });
        });
    }

    getActivedTab = () => {
        return this.state.tabKey;
    }

    onTabChange = (activeKey) => {

        this.setState({ tabKey: activeKey });

        setTimeout(() => {

            this.state.tabConfig.tabPageList.forEach(tab => {
                if (tab.name === activeKey && this.tabPanelRouter !== null) {
                    this.tabPanelRouter.goto(tab.compentclass);
                }
            });

            if (this.props.onTabChange !== undefined) {
                this.props.onTabChange(activeKey);
            }
        });

    }

    render() {

        const tabContentMap = this.props.tabContentMap;

        const tabs = this.state.tabConfig.tabPageList.map(tab => {

            return {
                key: tab.name,
                tab: <span key={tab.name}>{isEmpty(tab.icon) === false ? <UIIcon icon={tab.icon} /> : ''}{tab.label}</span>,
            };
        });

        const tabPanelProps = {
            ref: (inst) => this.tabPanelRouter = inst,
            pageInstance: this,
            contentMap: tabContentMap,
        }

        return (
            <Card
                tabList={tabs}
                bordered={this.props.bordered}
                loading={this.state.loading}
                onTabChange={this.onTabChange}
                extra={this.props.extra}
                title={this.props.title}
                type={this.props.type}
                activeTabKey={this.state.tabKey}>
                <UITabPanel {...tabPanelProps} />
            </Card>
        );
    }
}
